package alijk.dataView.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.Writer;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.PropertyException;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sun.xml.bind.marshaller.CharacterEscapeHandler;

import alijk.dataView.model.MessageBean;
import alijk.dataView.model.RequestBean;
import alijk.dataView.model.ResponseBean;
import alijk.dataView.utils.Constants;
import alijk.dataView.utils.JavaBeanUtils;
import flexjson.JSONDeserializer;

@Controller
@Scope(value = "prototype")
@RequestMapping("/weixin")
public class OpenWinXin {
	
	@RequestMapping("/check.do")
	@ResponseBody
	public String checkSignature(
			@RequestParam(value = "signature", required = false) String signature,
			@RequestParam(value = "timestamp", required = false) String timestamp,
			@RequestParam(value = "nonce", required = false) String nonce,
			@RequestParam(value = "echostr", required = false) String echostr){
		System.out.println("signature:"+signature+"\n"
						   +"timestamp"+timestamp+"\n"
						   +"nonce"+nonce+"\n"+"echostr"+echostr);
		
		return echostr;
	}
	
	public static  String getWeixinToken(){
		String url = "http://www.gpsspg.com/ajax/maps_get.aspx?lat=31.196752&lng=121.565054&type=0";
		HttpClient httpClient = new HttpClient();
		HttpMethod method = new GetMethod(url);
		String token = "";
		try {
			httpClient.executeMethod(method);
			
//			System.out.println(method.getResponseBodyAsString());
			JSONDeserializer<Map<String,Object>> json = new JSONDeserializer<Map<String,Object>>();
			Map<String,Object> map = json.deserialize(method.getResponseBodyAsString());
			System.out.println(map.get("address"));
//			token = map.get("access_token").toString();
			method.releaseConnection();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return token;
	}
	/**
	 * 属性变成 element
	 * <xml> 
		    <ToUserName>liyan</ToUserName>
		    <FromUserName>车文亮</FromUserName>
		    <CreateTime>1416640452121</CreateTime>
		    <MsgType>text</MsgType>
		    <Content>微信公众平台测试消息</Content>
		</xml>
	 * @return
	 */
	
	
	public static String javaBeanToXML(){
		MessageBean message = new MessageBean();
		message.setFromUserName("车文亮");
		message.setToUserName("liyan");
		message.setCreateTime(String.valueOf(new Date().getTime()));
		message.setMsgType("text");
		message.setContent("微信公众平台测试消息");
		String xml = JavaBeanUtils.convertToXml(message);
		return xml;
	}
	
	public static String getTemp(){
		//http://api.map.baidu.com/geocoder?location=30.990998,103.645966&output=json&key=28bcdd84fae25699606ffad27f8da77b
		String url_w = "http://api.map.baidu.com/telematics/v3/weather?location=南昌&output=json&ak=W69oaDTCfuGwzNwmtVvgWfGH";
		JSONDeserializer<Map<String,Object>> json = new JSONDeserializer<Map<String,Object>>();
		String token = "";
		StringBuffer weatherBuffer = new StringBuffer();
		try {
			URL url = new   URL( url_w);
			URLConnection uc = url.openConnection(); 
			InputStream is = uc.getInputStream(); 
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			StringBuffer stringBuffer = new StringBuffer();
			String line = null;
			while ((line = reader.readLine()) != null) {
				stringBuffer.append(line);
			}
		Map<String,Object> map = json.deserialize(stringBuffer.toString());
		List<Map<String,Object>> list_result = (List<Map<String, Object>>) map.get("results");
		Map<String,Object> map_result = list_result.get(0);
		
		weatherBuffer.append((String) map_result.get("currentCity")+"\n");
		
		List<Map<String,Object>> list_we = (List<Map<String, Object>>) map_result.get("weather_data");
		for(int i=0;i<list_we.size();i++){
			Map<String,Object> wether = list_we.get(i);
			String date = wether.get("date").toString();
			String weather_t =  wether.get("weather").toString();
			String temperature = wether.get("temperature").toString();
			weatherBuffer.append(date+",");
			weatherBuffer.append(weather_t+"  ");
			weatherBuffer.append(temperature+"  ");
			weatherBuffer.append("\n");
		}
		System.out.println(weatherBuffer.toString());
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return weatherBuffer.toString();
	}
	
	//http://php.weather.sina.com.cn/search.php?f=1&c=1&city=%E5%8D%97%E6%98%8C&dpc=1
	public static void main(String[] args) throws Exception {
//		getWeixinToken();
		getTemp();
//		System.out.println(javaBeanToXML());
//		String xml = "<xml><ToUserName><![CDATA[gh_c3082ec3a0bd]]></ToUserName><FromUserName><![CDATA[oaWEPs5VCB41orlzd3p6BeSuOOAk]]></FromUserName><CreateTime>1416819316</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[subscribe]]></Event><EventKey><![CDATA[]]></EventKey></xml>";
//		RequestBean bean  = JavaBeanUtils.converyToJavaBean(xml, RequestBean.class);
//		System.out.println(bean.getFromUserName());
//		System.out.println(bean.getMsgType());
//		ResponseBean respBean = new ResponseBean();
//		respBean.setFromUserName(bean.getFromUserName());
//		respBean.setToUserName(bean.getToUserName());
//		respBean.setMsgType("text");
//		respBean.setCreateTime(new Date().getTime());
//		respBean.setContent("asdfasdf");
//		String respBean1 = JavaBeanUtils.getResponseXml(bean,"chewl");
//		System.out.println(respBean1);
	}
}
